package com.yuzhitong.shapi.fragment;

import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bytedance.sdk.dp.DPSdk;
import com.bytedance.sdk.dp.DPWidgetDrawParams;
import com.bytedance.sdk.dp.IDPBannerListener;
import com.bytedance.sdk.dp.IDPWidget;
import com.flyco.tablayout.SlidingTabLayout;
import com.kwad.sdk.api.KsAdSDK;
import com.kwad.sdk.api.KsContentPage;
import com.kwad.sdk.api.KsFeedPage;
import com.kwad.sdk.api.KsLoadManager;
import com.kwad.sdk.api.KsScene;
import com.kwad.sdk.api.KsTubePage;
import com.yuzhitong.shapi.R;
import com.yuzhitong.shapi.base.BaseLayoutFragment;
import com.yuzhitong.shapi.base.Contents;
import com.yuzhitong.shapi.util.LoggerUtil;
import com.yuzhitong.shapi.util.UiUtil;

import java.util.Map;

/**
 * Created by Brsya
 * CreateDate: 2022/5/2  15:45
 * Description:
 * 视频页
 */
public class VideoFragment extends BaseLayoutFragment {
    private LinearLayout llTopTitle;
    private SlidingTabLayout tlTitleBox;
    private ViewPager vpVideoBox;


    private IDPWidget mIDPWidget;

    private Fragment ttFragment;
    private Fragment ksFragment;

    private int selectPosition;

    private Fragment ksVideoListFragment;
    private Fragment ksVideoFragment;
    private Handler mainHandler;
    private Runnable bookChangePaddingRunnable1;
    private Runnable bookChangePaddingRunnable2;


    public static VideoFragment newInstance() {

        Bundle args = new Bundle();

        VideoFragment fragment = new VideoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        setContentViewId(R.layout.fragment_video);
        llTopTitle = findViewById(R.id.ll_top_title);
        tlTitleBox = findViewById(R.id.tl_title_box);
        vpVideoBox = findViewById(R.id.vp_video_box);

    }

    @Override
    protected void initData() {
        llTopTitle.setPadding(
                llTopTitle.getPaddingLeft(),
                llTopTitle.getPaddingTop() + UiUtil.getStatusBarHeight(getContext()),
                llTopTitle.getPaddingRight(),
                llTopTitle.getPaddingBottom()
        );

        mainHandler = new Handler(Looper.getMainLooper());

        DPWidgetDrawParams params = DPWidgetDrawParams.obtain();
        params.mIsHideClose = true;

        LoggerUtil.i("状态栏高度:" + UiUtil.getStatusBarHeightDp(getContext()));
        params.titleTopMargin(UiUtil.getStatusBarHeightDp(getContext()));
        params.drawChannelType(DPWidgetDrawParams.DRAW_CHANNEL_TYPE_RECOMMEND);
        params.hideChannelName(true);
        params.drawContentType(DPWidgetDrawParams.DRAW_CONTENT_TYPE_ALL);
        params.hideFollow(true);
        params.listener(new IDPBannerListener() {
            @Override
            public void onDPVideoPause(Map<String, Object> map) {
                super.onDPVideoPause(map);
                getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            }

            @Override
            public void onDPVideoPlay(Map<String, Object> map) {
                super.onDPVideoPlay(map);
                getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            }
        });
        if (DPSdk.factory() == null) {
            Toast.makeText(getActivity(), "内容获取失败,请同意用户协议继续", Toast.LENGTH_SHORT).show();
            return;
        }
        mIDPWidget = DPSdk.factory().createDraw(params);
        ttFragment = mIDPWidget.getFragment();
        ttFragment.onPause();
        ttFragment.onHiddenChanged(true);
        ttFragment.setUserVisibleHint(false);

        KsScene adScene = new KsScene.Builder(Contents.KS_SDK_VIDEO_FRAGMENT_ID).build();
        KsLoadManager loadManager = KsAdSDK.getLoadManager();
        if (loadManager != null) {
            KsContentPage ksContentPage = loadManager.loadContentPage(adScene);
            ksFragment = ksContentPage.getFragment();
        }
        KsScene ksVideoListAdScene = new KsScene.Builder(Contents.KS_SDK_VIDEO_VIDEO_ID).build();
        KsFeedPage ksFeedPage = KsAdSDK.getLoadManager().loadFeedPage(ksVideoListAdScene);
        ksVideoListFragment = ksFeedPage.getFragment();


        KsScene scene = new KsScene.Builder(Contents.KS_SDK_VIDEO_ID)
                .needShowMiniWindow(false)
                .build();
        KsTubePage ksTubePage = loadManager.loadTubePage(scene, false);
        ksVideoFragment = ksTubePage.getFragment();

        vpVideoBox.setOffscreenPageLimit(10);
        vpVideoBox.setAdapter(new FragmentPagerAdapter(getChildFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                switch (position) {
                    case 3:
                        if (ttFragment == null) {
                            ttFragment = mIDPWidget.getFragment();
                        }
                        return ttFragment;
                    case 1:
                        if (ksVideoListFragment== null) {
                            KsScene adScene = new KsScene.Builder(Contents.KS_SDK_VIDEO_VIDEO_ID).build();
                            KsFeedPage ksFeedPage = KsAdSDK.getLoadManager().loadFeedPage(adScene);

                            ksVideoListFragment = ksFeedPage.getFragment();
                            return ksVideoListFragment;
                        }
                        if (bookChangePaddingRunnable1 == null) {
                            bookChangePaddingRunnable1 = new Runnable() {
                                @Override
                                public void run() {
                                    View rootView = ksVideoListFragment.getView();
                                    if (rootView == null) {
                                        mainHandler.postDelayed(bookChangePaddingRunnable1, 100);
                                        return;
                                    }
                                    rootView.setBackgroundColor(0xFF000000);
                                    rootView.setPadding(
                                            rootView.getPaddingLeft(),
                                            rootView.getPaddingTop() + getStatusBarHeight() + tlTitleBox.getHeight(),
                                            rootView.getPaddingRight(),
                                            rootView.getPaddingBottom()
                                    );
                                }
                            };
                        }
                        // 设置小说页面头部padding
                        mainHandler.postDelayed(bookChangePaddingRunnable1, 100);
                        return ksVideoListFragment;
                    case 2:
                        if (ksVideoFragment == null) {
                            KsScene scene = new KsScene.Builder(Contents.KS_SDK_VIDEO_ID)
                                    .needShowMiniWindow(false)
                                    .build();
                            KsTubePage ksTubePage = loadManager.loadTubePage(scene, false);
                            ksVideoFragment =  ksTubePage.getFragment();
                            return ksVideoFragment;
                        }
                        if (bookChangePaddingRunnable2 == null) {
                            bookChangePaddingRunnable2 = new Runnable() {
                                @Override
                                public void run() {
                                    View rootView = ksVideoFragment.getView();
                                    if (rootView == null) {
                                        mainHandler.postDelayed(bookChangePaddingRunnable2, 100);
                                        return;
                                    }
                                    rootView.setPadding(
                                            rootView.getPaddingLeft(),
                                            rootView.getPaddingTop() + getStatusBarHeight() + tlTitleBox.getHeight(),
                                            rootView.getPaddingRight(),
                                            rootView.getPaddingBottom()
                                    );
                                }
                            };
                        }
                        // 设置小说页面头部padding
                        mainHandler.postDelayed(bookChangePaddingRunnable2, 100);
                        return ksVideoFragment;
                    case 0:
                    default:
                        if (ksFragment == null) {
                            KsLoadManager loadManager = KsAdSDK.getLoadManager();
                            KsScene adScene2 = new KsScene.Builder(Contents.KS_SDK_VIDEO_FRAGMENT_ID).build();
                            if (loadManager != null) {
                                KsContentPage ksContentPage = loadManager.loadContentPage(adScene2);

                                ksFragment = ksContentPage.getFragment();
                            } else {
                                LoggerUtil.e("快手短视频获取为空");
                                return ttFragment;
                            }
                        }
                        return ksFragment;
                }
            }

            @Override
            public int getCount() {
                return 4;
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 1:
                        return "视频";
                    case 2:
                        return "短剧";
                    case 3:
                        return "更多";
                    case 0:
                    default:
                        return "热门";
                }
            }
        });

        vpVideoBox.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 3) {
                    ttFragment.setUserVisibleHint(true);
                }else{
                    ttFragment.setUserVisibleHint(false);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


        tlTitleBox.setViewPager(vpVideoBox);

        KsAdSDK.setThemeMode(KsAdSDK.KsThemeModeType.NIGHT);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        // 解决穿山甲视频切换Activity后自动播放问题
        if (hidden) {
            selectPosition = vpVideoBox.getCurrentItem();
            vpVideoBox.setCurrentItem(0, false);
        } else {
            if (selectPosition == 0 && isResumed()) {
                vpVideoBox.setCurrentItem(0, false);
            }
        }
    }


    /**
     * 获取状态栏高度
     */
    public int getStatusBarHeight() {
        Resources resources = getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);
        return height;
    }
}
